/*
  学习目标：退出登录
  步骤：
     0. 二次确认
     1. 删token
     2. 跳路由
     3. 提示用户
*/

import NavBar from "@/components/NavBar";
import { List, Modal, Popup, Toast } from "antd-mobile";
import styles from "./index.module.scss";
import { useAppDispatch, useAppSelector } from "@/store";
import { useEffect, useRef, useState } from "react";
import {
  getProfileAction,
  updatePhotoAction,
  updateProfileAction,
} from "@/store/action/user";
import { IProfile } from "@/store/reducer/user";
import Input from "@/components/Input";
import TextArea from "@/components/TextArea";
import { DatePicker } from "antd-mobile";
import dayjs from "dayjs";
import { removeAuth } from "@/utils/storage";
import history from "@/utils/history";

type EditType = "photo" | "gender" | "name" | "intro";

export default function ProfileEdit() {
  const { profile } = useAppSelector((state) => state.uer);
  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);

  const [name, setName] = useState("");
  const [intro, setIntro] = useState("");

  useEffect(() => {
    setName(profile.name);
    setIntro(profile.intro || "");
  }, [profile]);
  const [editType, setEditType] = useState("" as EditType);
  const uploadRef = useRef<HTMLInputElement>(null);
  const dispatch = useAppDispatch();
  useEffect(() => {
    dispatch(getProfileAction());
  }, [dispatch]);

  const handleShowUpload = () => {
    uploadRef.current?.click();
  };

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) {
      const formData = new FormData();
      formData.append("photo", e.target.files[0]);
      await dispatch(updatePhotoAction(formData));

      handleRefresh();
    }
  };

  const handleShowPopup = (type: EditType) => {
    setEditType(type);
    if (type === "photo" || type === "gender") setVisible(true);
    if (type === "name" || type === "intro") setRightVisible(true);
  };

  const handleRefresh = () => {
    dispatch(getProfileAction());
    setVisible(false);
    setRightVisible(false);
    Toast.show({ content: "更新成功", icon: "success" });
  };

  const handleUpdateProfile = async (profile: Partial<IProfile>) => {
    await dispatch(updateProfileAction(profile));
    handleRefresh();
  };

  const renderPhotoOrGender = () => {
    if (editType === "photo") {
      return (
        <>
          <div onClick={handleShowUpload} className="list-item">
            拍照
          </div>
          <div onClick={handleShowUpload} className="list-item">
            本地选择
          </div>
          <div onClick={() => setVisible(false)} className="list-item">
            取消
          </div>
        </>
      );
    }

    if (editType === "gender") {
      return (
        <>
          <div
            className="list-item"
            onClick={() => handleUpdateProfile({ gender: 0 })}
          >
            男
          </div>
          <div
            className="list-item"
            onClick={() => handleUpdateProfile({ gender: 1 })}
          >
            女
          </div>
          <div onClick={() => setVisible(false)} className="list-item">
            取消
          </div>
        </>
      );
    }
  };
  const handleBack = () => {
    setRightVisible(false);
    setName(profile.name);
    setIntro(profile.intro || "");
  };

  const renderNameOrIntro = () => {
    const params = {} as IProfile;
    if (editType === "name") params.name = name;
    if (editType === "intro") params.intro = intro;

    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span
              onClick={() => handleUpdateProfile(params)}
              className="submit-btn"
            >
              提交
            </span>
          }
        />
        <div className="edit-content">
          {editType === "name" && (
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="edit-input"
            />
          )}
          {editType === "intro" && (
            <TextArea
              value={intro}
              onChange={(e) => setIntro(e.target.value)}
            />
          )}
        </div>
      </>
    );
  };

  const handleLoginOut = () => {
    // 0. 二次确认
    Modal.confirm({
      title: "温馨提示",
      content: "确定退出登录吗?",
      onConfirm: () => {
        // 1. 删token
        removeAuth();
        // 2. 跳路由
        history.push("/");
        // 3. 提示用户
        Toast.show({ content: "退出成功", icon: "success" });
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handleShowPopup("photo")}
            >
              头像
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup("name")}
              arrow
              extra={profile.name}
            >
              昵称
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup("intro")}
              arrow
              extra={<span className="intro">{profile.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup("gender")}
              arrow
              extra={profile.gender === 0 ? "男" : "女"}
            >
              性别
            </List.Item>
            <List.Item
              onClick={() => setBirthVisible(true)}
              arrow
              extra={profile.birthday}
            >
              生日
            </List.Item>
          </List>

          <input
            onChange={handleUpload}
            ref={uploadRef}
            className="avatar-upload"
            type="file"
          />
        </div>

        <div className="logout">
          <button onClick={handleLoginOut} className="btn">
            退出登录
          </button>
        </div>
      </div>
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
      >
        {renderPhotoOrGender()}
      </Popup>
      <Popup
        destroyOnClose
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
      >
        {renderNameOrIntro()}
      </Popup>
      <DatePicker
        onClose={() => setBirthVisible(false)}
        onConfirm={(val) => {
          handleUpdateProfile({ birthday: dayjs(val).format("YYYY-MM-DD") });
        }}
        min={new Date("1900-01-01")}
        max={new Date()}
        value={new Date(profile.birthday)}
        visible={birthVisible}
      />
    </div>
  );
}
